<template>
    <div class="product-add-container">
        <div class="page-header">
            <h2>添加货品信息</h2>
        </div>

        <div class="form-container">
            <el-form :model="formData" :rules="rules" ref="productFormRef" label-width="120px">
                <el-card class="form-card">
                    <template #header>
                        <span class="card-title">基础信息</span>
                    </template>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="货品编号" prop="goodsCode">
                                <el-input v-model="formData.goodsCode" placeholder="请输入货品编号" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="货品名称" prop="goodsName">
                                <el-input v-model="formData.goodsName" placeholder="请输入货品名称" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="货品类型" prop="productTypeId">
                                <el-select v-model="formData.productTypeId" placeholder="请选择货品类型" clearable filterable
                                    style="width: 100%">
                                    <el-option v-for="item in productTypeOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="规格型号" prop="specModel">
                                <el-input v-model="formData.specModel" placeholder="请输入规格型号" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="供应商" prop="supplierId">
                                <el-select v-model="formData.supplierId" placeholder="请选择供应商" clearable filterable
                                    style="width: 100%">
                                    <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="客户名称" prop="userId">
                                <el-select v-model="formData.userId" placeholder="请选择客户" clearable filterable
                                    style="width: 100%" @change="handleUserChange" @focus="handleUserFocus">
                                    <el-option v-for="item in userOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="入库参考价/元" prop="purchasePrice">
                                <el-input-number v-model="formData.purchasePrice" :precision="2" :min="0"
                                    style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="出库参考价/元" prop="salePrice">
                                <el-input-number v-model="formData.salePrice" :precision="2" :min="0"
                                    style="width: 100%" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="显示顺序" prop="displayOrder">
                                <el-input-number v-model="formData.displayOrder" :min="0" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态" prop="status">
                                <el-radio-group v-model="formData.status">
                                    <el-radio :label="1">启用</el-radio>
                                    <el-radio :label="0">停用</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="保质期管理">
                                <el-switch v-model="formData.shelfLifeManagement" :active-value="1"
                                    :inactive-value="0" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <template v-if="formData.shelfLifeManagement === 1">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="保质期时长" prop="shelfLife">
                                    <el-input-number v-model="formData.shelfLife" :min="0" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="保质期单位" prop="shelfLifeUnit">
                                    <el-select v-model="formData.shelfLifeUnit" placeholder="请选择单位" style="width: 100%">
                                        <el-option label="天" value="天" />
                                        <el-option label="月" value="月" />
                                        <el-option label="年" value="年" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="预警天数" prop="warningDays">
                                    <el-input-number v-model="formData.warningDays" :min="0" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </template>

                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="备注" prop="notes">
                                <el-input v-model="formData.notes" type="textarea" :rows="4" placeholder="请输入备注" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>

                <!-- 单位管理部分 -->
                <el-card class="form-card unit-card">
                    <template #header>
                        <span class="card-title">单位管理</span>
                    </template>

                    <div class="unit-management">
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-checkbox v-model="formData.enableMultiUnit">启用多单位</el-checkbox>
                            </el-col>
                        </el-row>

                        <div class="unit-list" v-if="formData.enableMultiUnit">
                            <div v-for="(unit, index) in formData.unitList" :key="index" class="unit-item">
                                <el-row :gutter="20" align="middle">
                                    <el-col :span="1">
                                        <span class="required-mark" v-if="index === 0">*</span>
                                    </el-col>
                                    <el-col :span="3">
                                        <span class="unit-label">{{ index === 0 ? '主单位' : '辅助单位' }}</span>
                                    </el-col>
                                    <el-col :span="6">
                                        <el-select v-model="unit.unitId" placeholder="请选择" clearable filterable
                                            style="width: 100%" @change="handleUnitChange(index, unit.unitId)">
                                            <el-option v-for="item in unitOptions" :key="item.value" :label="item.label"
                                                :value="item.value" />
                                        </el-select>
                                    </el-col>
                                    <el-col :span="6">
                                        <el-input v-model="unit.unitCode" placeholder="请输入">
                                            <template #append>
                                                <el-button type="primary" link @click="generateUnitCode(index)">生成条码
                                                </el-button>
                                            </template>
                                        </el-input>
                                    </el-col>
                                    <el-col :span="1" v-if="index > 0">
                                        <span class="unit-divider">瓶</span>
                                    </el-col>
                                    <el-col :span="5" v-if="index > 0">
                                        <el-input v-model="unit.conversion" placeholder="请输入">
                                            <template #append>
                                                <el-button type="primary" link
                                                    @click="generateConversionCode(index)">生成条码
                                                </el-button>
                                            </template>
                                        </el-input>
                                    </el-col>
                                    <el-col :span="1" v-if="index > 0">
                                        <span class="unit-divider">箱</span>
                                    </el-col>
                                    <el-col :span="1">
                                        <el-button-group>
                                            <el-button v-if="index === formData.unitList.length - 1" circle size="small"
                                                @click="addUnit">
                                                <el-icon>
                                                    <Plus />
                                                </el-icon>
                                            </el-button>
                                            <el-button v-if="index > 0" circle size="small" @click="removeUnit(index)">
                                                <el-icon>
                                                    <Minus />
                                                </el-icon>
                                            </el-button>
                                        </el-button-group>
                                    </el-col>
                                </el-row>
                            </div>
                        </div>
                    </div>
                </el-card>

                <!-- 库存信息部分 -->
                <el-card class="form-card inventory-card">
                    <template #header>
                        <div class="card-header-wrapper">
                            <span class="card-title">库存信息</span>
                            <el-checkbox v-model="formData.initInventory" style="margin-left: auto;">初始库存</el-checkbox>
                        </div>
                    </template>

                    <div class="inventory-error-tip" v-if="inventoryError">
                        <el-icon color="#f56c6c">
                            <CircleClose />
                        </el-icon>
                        <span>{{ inventoryError }}</span>
                    </div>

                    <div class="inventory-management">
                        <div class="inventory-actions">
                            <el-button type="success" @click="addInventoryRow">添加</el-button>
                            <el-button @click="removeSelectedInventory">移除</el-button>
                        </div>

                        <div class="inventory-table">
                            <el-table :data="formData.inventoryList" border style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column label="期初仓库" width="150" align="center">
                                    <template #default="{ row }">
                                        <span>{{ row.warehouseName || '仓库一' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="期初库存" width="180" align="center">
                                    <template #default="{ row, $index }">
                                        <el-input v-model="row.initialQty" placeholder="请输入">
                                            <template #append>
                                                <el-button type="primary" link
                                                    @click="openBatchDialog($index, row)">批次</el-button>
                                            </template>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="期初库存金额" width="120" align="center">
                                    <template #default="{ row }">
                                        <div class="amount-display">{{ row.initialAmount || 0 }} 元</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="库存上限" width="180" align="center">
                                    <template #default="{ row }">
                                        <el-input v-model="row.upperLimit" placeholder="请输入">
                                            <template #append>
                                                <el-button type="primary" link>批量</el-button>
                                            </template>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="库存下线" width="180" align="center">
                                    <template #default="{ row }">
                                        <el-input v-model="row.lowerLimit" placeholder="请输入">
                                            <template #append>
                                                <el-button type="primary" link>批量</el-button>
                                            </template>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="备注" min-width="200">
                                    <template #default="{ row }">
                                        <el-input v-model="row.remark" placeholder="请输入" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="100" align="center" fixed="right">
                                    <template #default="{ $index }">
                                        <el-button type="success" link
                                            @click="removeInventoryRow($index)">移除</el-button>
                                    </template>
                                </el-table-column>
                                <template #empty>
                                    <div class="empty-tip">
                                        <p>暂无库存数据</p>
                                        <el-button type="primary" size="small"
                                            @click="addInventoryRow">点击添加仓库</el-button>
                                    </div>
                                </template>
                            </el-table>
                        </div>
                    </div>
                </el-card>

                <div class="form-footer">
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">保存</el-button>
                    <el-button @click="handleCancel">取消</el-button>
                </div>
            </el-form>
        </div>

        <!-- 仓库选择对话框 -->
        <el-dialog v-model="warehouseDialogVisible" title="选择仓库" width="80%" :close-on-click-modal="false">
            <div class="warehouse-dialog-content">
                <el-table :data="warehouseList" border style="width: 100%" @row-click="handleWarehouseRowClick"
                    highlight-current-row max-height="400">
                    <el-table-column type="selection" width="55" />
                    <el-table-column type="index" label="序号" width="60" align="center" />
                    <el-table-column prop="warehouseCode" label="仓库编号" width="120" align="center" />
                    <el-table-column prop="warehouseName" label="仓库名称" width="150" align="center" />
                    <el-table-column prop="capacity" label="仓库容量/m³" width="120" align="center" />
                    <el-table-column prop="warehouseAddress" label="仓库地址" min-width="200" />
                    <el-table-column prop="department" label="仓库部门" width="120" align="center" />
                    <el-table-column prop="manager" label="仓库主管" width="120" align="center" />
                    <el-table-column prop="status" label="仓库状态" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag :type="row.status === '启用' ? 'success' : 'info'">{{ row.status }}</el-tag>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination-wrapper">
                    <el-pagination v-model:current-page="warehousePagination.page"
                        v-model:page-size="warehousePagination.rows" :page-sizes="[10, 20, 30, 50]"
                        :total="warehousePagination.total" layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleWarehouseSizeChange" @current-change="handleWarehousePageChange" />
                </div>
            </div>

            <template #footer>
                <el-button @click="warehouseDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleWarehouseConfirm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 批次管理对话框 -->
        <el-dialog v-model="batchDialogVisible" title="批次管理" width="600px" :close-on-click-modal="false">
            <div class="batch-dialog-content">
                <div class="batch-table">
                    <el-table :data="batchList" border style="width: 100%">
                        <el-table-column type="index" label="序号" width="60" align="center" />
                        <el-table-column label="数量" width="120" align="center">
                            <template #default="{ row }">
                                <el-input v-model="row.quantity" placeholder="请输入" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="批次" width="120" align="center">
                            <template #default="{ row }">
                                <el-input v-model="row.batchNo" placeholder="请输入" />
                            </template>
                        </el-table-column>
                        <el-table-column label="生产日期" width="170" align="center">
                            <template #default="{ row }">
                                <el-date-picker v-model="row.productionDate" type="date" placeholder="yyyy/mm/dd"
                                    format="YYYY/MM/DD" value-format="YYYY-MM-DD" style="width: 100%;" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="130" align="center" fixed="right">
                            <template #default="{ $index }">
                                <template v-if="$index === batchList.length - 1 && batchList.length === 1">
                                    <el-button type="success" link @click="addBatchRow">添加</el-button>
                                </template>
                                <template v-else-if="$index === batchList.length - 1">
                                    <el-button type="success" link @click="addBatchRow">添加</el-button>
                                    <el-button type="danger" link @click="removeBatchRow($index)">移除</el-button>
                                </template>
                                <template v-else>
                                    <el-button type="danger" link @click="removeBatchRow($index)">移除</el-button>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <div class="batch-summary">
                    <span>批次总数：<span class="total-count">{{ batchTotalCount }}</span></span>
                </div>
            </div>

            <template #footer>
                <el-button @click="batchDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleBatchConfirm" :loading="batchSubmitLoading">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Minus, CircleClose } from '@element-plus/icons-vue';

const router = useRouter();
const { proxy } = getCurrentInstance();
const productFormRef = ref(null);
const submitLoading = ref(false);

// 下拉选项数据
const productTypeOptions = ref([]);
const supplierOptions = ref([]);
const userOptions = ref([]);
const unitOptions = ref([]);

// 库存管理相关
const inventoryError = ref('');
const warehouseDialogVisible = ref(false);
const warehouseList = ref([]);
const selectedWarehouse = ref(null);
const currentInventoryIndex = ref(-1);

// 仓库分页数据
const warehousePagination = reactive({
    page: 1,
    rows: 10,
    total: 0
});

// 批次管理相关
const batchDialogVisible = ref(false);
const batchList = ref([]);
const currentBatchInventoryIndex = ref(-1);
const currentBatchRow = ref(null);
const batchSubmitLoading = ref(false);
const batchTotalCount = computed(() => {
    return batchList.value.reduce((total, item) => {
        return total + (parseFloat(item.quantity) || 0);
    }, 0);
});

// 表单数据
const formData = reactive({
    id: 0,
    goodsCode: '',
    goodsName: '',
    status: 1,
    productTypeId: null,
    specModel: '',
    supplierId: null,
    userId: '', // 改为空字符串，因为可能是字符串类型
    purchasePrice: 0,
    salePrice: 0,
    displayOrder: 0,
    currentInventory: 0,
    totalInventoryamount: 0,
    shelfLifeManagement: 0,
    shelfLife: 0,
    shelfLifeUnit: '天',
    warningDays: 0,
    notes: '',
    isDel: 0,
    unitId: 0,
    creator: '',
    createDate: '',
    modifier: '',
    modifyDate: '',
    createID: 0,
    modifyID: 0,
    typeName: '',
    unitName: '',
    // 单位管理
    enableMultiUnit: false,
    unitList: [
        {
            unitId: null,
            unitCode: '',
            conversion: '',
            isPrimary: true
        }
    ],
    // 库存管理
    initInventory: true,
    inventoryList: []
});

// 表单验证规则
const rules = {
    goodsCode: [
        { required: true, message: '请输入货品编号', trigger: 'blur' }
    ],
    goodsName: [
        { required: true, message: '请输入货品名称', trigger: 'blur' }
    ],
    productTypeId: [
        { required: true, message: '请选择货品类型', trigger: 'change' }
    ],
    supplierId: [
        { required: true, message: '请选择供应商', trigger: 'change' }
    ]
};

// 加载货品类型数据
const loadProductTypes = async () => {
    try {
        const response = await proxy.http.get('/api/producttypemodel/GetCascadeList');
        const data = Array.isArray(response) ? response : response?.data || [];

        productTypeOptions.value = data.map(item => ({
            value: parseInt(item.id || 0),
            label: item.typeName || ''
        }));
    } catch (error) {
        console.error('加载货品类型失败:', error);
    }
};

// 加载供应商数据
const loadSuppliers = async () => {
    try {
        const response = await proxy.http.get('/api/InboundManagement/GetSupplierOptions');

        if (response?.success && response?.data) {
            supplierOptions.value = response.data.map(item => ({
                value: parseInt(item.id || 0),
                label: item.supplierName || ''
            }));
        }
    } catch (error) {
        console.error('加载供应商失败:', error);
    }
};

// 加载用户数据
const loadUsers = async () => {
    try {
        const response = await proxy.http.post('/api/User/GetPageData', {
            page: 0,
            rows: 0,
            total: 0,
            tableName: "string",
            wheres: "string",
            order: "string",
            export: true,
            value: "string",
            filter: []
        });
        console.log('===== 用户数据API响应 =====');
        console.log('完整响应:', response);

        if (response && response.rows && Array.isArray(response.rows)) {
            userOptions.value = response.rows.map(item => {
                console.log('处理用户项:', item);
                return {
                    value: item.user_id || item.User_Id,
                    label: item.userTrueName || item.UserTrueName || item.userName || item.UserName || `用户${item.user_id}`
                };
            });
            console.log('最终用户选项数量:', userOptions.value.length);
            console.log('用户选项列表:', userOptions.value);
        } else {
            console.error('用户数据格式不正确或为空');
            ElMessage.warning('加载客户数据失败');
        }
    } catch (error) {
        console.error('加载用户失败:', error);
        ElMessage.error('加载客户数据时发生错误');
    }
};

// 加载单位数据
const loadUnits = async () => {
    try {
        const response = await proxy.http.post('/api/UnitModel/GetPageData', {
            page: 0,
            rows: 0,
            total: 0,
            tableName: "string",
            wheres: "string",
            order: "string",
            export: true,
            value: "string",
            filter: []
        });

        if (response && response.rows && Array.isArray(response.rows)) {
            unitOptions.value = response.rows.map(item => ({
                value: item.id || item.Id,
                label: item.unitName || item.UnitName || ''
            }));
            console.log('单位选项加载成功:', unitOptions.value);
        }
    } catch (error) {
        console.error('加载单位失败:', error);
    }
};

// 处理客户获得焦点
const handleUserFocus = () => {
    console.log('客户下拉框获得焦点，当前选项数量:', userOptions.value.length);
    if (!userOptions.value || userOptions.value.length === 0) {
        console.log('选项为空，重新加载...');
        loadUsers();
    }
};

// 处理客户选择变化
const handleUserChange = (value) => {
    console.log('选择的客户ID:', value);
    console.log('当前formData.userId:', formData.userId);
};

// 处理单位选择变化
const handleUnitChange = (index, unitId) => {
    console.log('选择单位 - 索引:', index, '单位ID:', unitId);

    // 如果是主单位（index === 0），则将该单位ID赋值给formData.unitId
    if (index === 0) {
        formData.unitId = unitId || 0;
        console.log('主单位已设置，formData.unitId:', formData.unitId);

        // 可选：获取单位名称并赋值
        const selectedUnit = unitOptions.value.find(item => item.value === unitId);
        if (selectedUnit) {
            formData.unitName = selectedUnit.label;
            console.log('主单位名称:', formData.unitName);
        }
    }
};

// 添加单位
const addUnit = () => {
    formData.unitList.push({
        unitId: null,
        unitCode: '',
        conversion: '',
        isPrimary: false
    });
};

// 移除单位
const removeUnit = (index) => {
    if (formData.unitList.length > 1) {
        formData.unitList.splice(index, 1);
    }
};

// 生成单位条码
const generateUnitCode = (index) => {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000);
    formData.unitList[index].unitCode = `UNIT${timestamp}${random}`;
    ElMessage.success('条码生成成功');
};

// 生成换算条码
const generateConversionCode = (index) => {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 1000);
    formData.unitList[index].conversion = `${random}`;
    ElMessage.success('条码生成成功');
};

// 库存管理相关方法

// 添加库存行
const addInventoryRow = () => {
    openWarehouseDialog();
};

// 移除选中的库存
const removeSelectedInventory = () => {
    if (formData.inventoryList.length === 0) {
        ElMessage.warning('没有可移除的库存信息');
        return;
    }
    // 可以在这里实现多选移除逻辑
    ElMessage.info('请点击行末的移除按钮来删除对应的库存行');
};

// 移除库存行
const removeInventoryRow = (index) => {
    formData.inventoryList.splice(index, 1);
    ElMessage.success('移除成功');
};

// 打开仓库选择对话框
const openWarehouseDialog = (index = -1) => {
    currentInventoryIndex.value = index;
    warehouseDialogVisible.value = true;
    loadWarehouses();
};

// 加载仓库数据
const loadWarehouses = async () => {
    try {
        const response = await proxy.http.post('/api/warehousemodel/GetPageData', {
            page: warehousePagination.page,
            rows: warehousePagination.rows,
            total: 0,
            tableName: "string",
            wheres: "string",
            order: "string",
            export: false,
            value: "string",
            filter: []
        });

        console.log('仓库数据响应:', response);

        if (response && response.rows && Array.isArray(response.rows)) {
            warehouseList.value = response.rows.map(item => ({
                id: item.id || item.Id,
                warehouseCode: item.warehouseCode || item.WarehouseCode || '',
                warehouseName: item.warehouseName || item.WarehouseName || '',
                capacity: item.capacity || item.Capacity || 0,
                warehouseAddress: item.warehouseAddress || item.WarehouseAddress || '',
                department: item.department || item.Department || '',
                manager: item.manager || item.Manager || '',
                status: item.status === 1 || item.Status === 1 ? '启用' : (item.status === 0 || item.Status === 0 ? '停用' : '已锁定')
            }));

            warehousePagination.total = response.total || 0;
            console.log('仓库列表加载成功，总数:', warehousePagination.total);
        }
    } catch (error) {
        console.error('加载仓库失败:', error);
        ElMessage.error('加载仓库数据失败');
    }
};

// 仓库分页大小改变
const handleWarehouseSizeChange = (val) => {
    warehousePagination.rows = val;
    loadWarehouses();
};

// 仓库分页页码改变
const handleWarehousePageChange = (val) => {
    warehousePagination.page = val;
    loadWarehouses();
};

// 仓库行点击
const handleWarehouseRowClick = (row) => {
    selectedWarehouse.value = row;
};

// 确认选择仓库
const handleWarehouseConfirm = () => {
    if (!selectedWarehouse.value) {
        ElMessage.warning('请选择一个仓库');
        return;
    }

    // 检查是否已经添加过该仓库
    const existingIndex = formData.inventoryList.findIndex(
        item => item.warehouseId === selectedWarehouse.value.id
    );

    if (existingIndex !== -1) {
        ElMessage.warning('该仓库已存在，不能重复添加');
        return;
    }

    // 添加新的库存行
    formData.inventoryList.push({
        warehouseId: selectedWarehouse.value.id,
        warehouseName: selectedWarehouse.value.warehouseName,
        initialQty: '',
        initialAmount: 0,
        upperLimit: '',
        lowerLimit: '',
        remark: '',
        batchList: [] // 初始化批次列表
    });

    ElMessage.success('添加仓库成功');
    warehouseDialogVisible.value = false;
    selectedWarehouse.value = null;
};

// 验证库存数据
const validateInventory = () => {
    inventoryError.value = '';

    if (!formData.initInventory) {
        return true;
    }

    // 检查库存上限是否大于库存下线
    for (let i = 0; i < formData.inventoryList.length; i++) {
        const item = formData.inventoryList[i];
        const upperLimit = parseFloat(item.upperLimit) || 0;
        const lowerLimit = parseFloat(item.lowerLimit) || 0;

        if (upperLimit > 0 && lowerLimit > 0 && upperLimit < lowerLimit) {
            inventoryError.value = '库存上限应大于库存下限！';
            return false;
        }
    }

    return true;
};

// 批次管理相关方法

// 打开批次对话框
const openBatchDialog = (index, row) => {
    currentBatchInventoryIndex.value = index;
    currentBatchRow.value = row;

    // 如果该库存行已有批次数据，则加载现有数据
    if (row.batchList && row.batchList.length > 0) {
        batchList.value = row.batchList.map(batch => ({
            quantity: batch.quantity.toString(),
            batchNo: batch.batchNo,
            productionDate: batch.productionDate
        }));
    } else {
        // 初始化批次列表，至少有一行
        batchList.value = [
            {
                quantity: '',
                batchNo: '',
                productionDate: ''
            }
        ];
    }

    batchDialogVisible.value = true;
};

// 添加批次行
const addBatchRow = () => {
    batchList.value.push({
        quantity: '',
        batchNo: '',
        productionDate: ''
    });
};

// 移除批次行
const removeBatchRow = (index) => {
    if (batchList.value.length > 1) {
        batchList.value.splice(index, 1);
    }
};

// 确认批次
const handleBatchConfirm = () => {
    // 验证批次数据
    const validBatches = batchList.value.filter(batch => {
        return batch.quantity && batch.batchNo;
    });

    if (validBatches.length === 0) {
        ElMessage.warning('请至少填写一条完整的批次信息（数量和批次号）');
        return;
    }

    // 暂存批次数据到当前库存行
    if (currentBatchRow.value) {
        // 保存批次信息到库存行的批次列表
        currentBatchRow.value.batchList = validBatches.map(batch => ({
            quantity: parseFloat(batch.quantity) || 0,
            batchNo: batch.batchNo,
            productionDate: batch.productionDate || ''
        }));

        // 更新期初库存数量为批次总数
        currentBatchRow.value.initialQty = batchTotalCount.value.toString();

        console.log('批次数据已暂存:', currentBatchRow.value.batchList);
    }

    ElMessage.success('批次信息已保存，将在货品保存时一并提交');
    batchDialogVisible.value = false;
};

// 提交批次数据到服务器
const submitBatchData = async (goodsId, warehouseId, batchList) => {
    try {
        console.log('submitBatchData 参数:');
        console.log('- goodsId:', goodsId, '(类型:', typeof goodsId, ')');
        console.log('- warehouseId:', warehouseId, '(类型:', typeof warehouseId, ')');
        console.log('- batchList:', batchList);

        // 确保ID为数字类型
        const numericGoodsId = parseInt(goodsId) || 0;
        const numericWarehouseId = parseInt(warehouseId) || 0;

        console.log('转换后的ID:');
        console.log('- goodsId:', numericGoodsId);
        console.log('- warehouseId:', numericWarehouseId);

        // 验证批次数据
        if (!batchList || batchList.length === 0) {
            throw new Error('批次列表为空');
        }

        // 获取当前时间
        const now = new Date().toISOString();

        // 构建批次数组数据
        const batchDataArray = batchList.map((batch, index) => {
            console.log(`处理批次 ${index + 1}:`, batch);

            // 处理生产日期
            let productionDate = batch.productionDate;
            if (productionDate && !productionDate.includes('T')) {
                // 如果只有日期没有时间，添加时间部分
                productionDate = productionDate + 'T00:00:00.000Z';
            } else if (!productionDate) {
                productionDate = now;
            }

            return {
                id: 0,
                goodsId: numericGoodsId,
                warehouseId: numericWarehouseId,
                batchNo: (batch.batchNo || '').toString().trim(),
                productionDate: productionDate,
                quantity: parseFloat(batch.quantity) || 0,
                expiryDate: now,
                label: 0,
                creator: 'admin',
                createDate: now,
                modifier: 'admin',
                modifyDate: now,
                createID: 0,
                modifyID: 0
            };
        });

        console.log('构建的批次数组数据:', JSON.stringify(batchDataArray, null, 2));

        // 验证数据完整性
        for (let i = 0; i < batchDataArray.length; i++) {
            const batch = batchDataArray[i];
            if (!batch.batchNo || batch.batchNo.trim() === '') {
                throw new Error(`批次 ${i + 1} 的批次号不能为空`);
            }
            if (!batch.quantity || batch.quantity <= 0) {
                throw new Error(`批次 ${i + 1} 的数量必须大于0`);
            }
            if (!batch.goodsId || batch.goodsId <= 0) {
                throw new Error(`货品ID无效: ${batch.goodsId}`);
            }
            if (!batch.warehouseId || batch.warehouseId <= 0) {
                throw new Error(`仓库ID无效: ${batch.warehouseId}`);
            }
        }

        console.log('✓ 批次数据验证通过，准备提交...');

        // 调用批次批量添加接口
        const response = await proxy.http.post('/api/GoodsBath/BatchAddGoodsBatch', batchDataArray);

        console.log('批次添加API响应:', response);
        console.log('批次响应完整数据:', JSON.stringify(response, null, 2));

        return response;
    } catch (error) {
        console.error('❌ 提交批次数据异常:', error);
        console.error('错误详情:', error?.response?.data || error?.message);
        throw error;
    }
};

// 提交表单
const handleSubmit = async () => {
    if (!productFormRef.value) return;

    try {
        const valid = await productFormRef.value.validate();
        if (!valid) return;

        // 前端再次验证货品编号
        if (!formData.goodsCode || formData.goodsCode.trim() === '') {
            ElMessage.error('货品编号不能为空');
            return;
        }

        // 验证库存数据
        if (!validateInventory()) {
            return;
        }

        submitLoading.value = true;

        // 准备提交数据，确保字符串字段被trim处理
        const submitData = {
            ...formData,
            // 字符串字段处理
            goodsCode: (formData.goodsCode || '').toString().trim(),
            goodsName: (formData.goodsName || '').toString().trim(),
            specModel: (formData.specModel || '').toString().trim(),
            notes: (formData.notes || '').toString().trim(),
            shelfLifeUnit: (formData.shelfLifeUnit || '天').toString(),
            // 确保数值类型正确
            productTypeId: parseInt(formData.productTypeId) || 0,
            supplierId: parseInt(formData.supplierId) || 0,
            // userId 保持原始类型（可能是字符串或数字）
            userId: formData.userId || 0,
            purchasePrice: Number(formData.purchasePrice) || 0,
            salePrice: Number(formData.salePrice) || 0,
            displayOrder: Number(formData.displayOrder) || 0,
            currentInventory: Number(formData.currentInventory) || 0,
            totalInventoryamount: Number(formData.totalInventoryamount) || 0,
            shelfLife: Number(formData.shelfLife) || 0,
            warningDays: Number(formData.warningDays) || 0,
            status: Number(formData.status) || 1,
            shelfLifeManagement: Number(formData.shelfLifeManagement) || 0,
            isDel: 0,
            unitId: Number(formData.unitId) || 0
        };

        console.log('=== 开始提交货品数据 ===');
        console.log('货品编号:', submitData.goodsCode);
        console.log('货品名称:', submitData.goodsName);
        console.log('单位ID (UnitId):', submitData.unitId);
        console.log('单位名称:', submitData.unitName);
        console.log('完整提交数据:', JSON.stringify(submitData, null, 2));

        // 调用API - 添加货品
        const response = await proxy.http.post('/api/demo/ProductInformation/Add', submitData);

        console.log('======= 货品添加API响应 =======');
        console.log('1. response原始对象:', response);
        console.log('2. response类型:', typeof response);

        // 打印所有层级的键
        if (response) {
            console.log('3. response的键:', Object.keys(response));

            // 如果response直接是数据对象
            if (typeof response === 'object') {
                for (const key in response) {
                    const value = response[key];
                    console.log(`   - ${key}:`, typeof value, Array.isArray(value) ? '(数组)' : '', value);
                }
            }
        }

        console.log('4. 响应完整JSON:', JSON.stringify(response, null, 2));

        // 如果有data属性，打印data的键
        if (response?.data) {
            console.log('response.data:', response.data);
            console.log('response.data类型:', typeof response.data);
            console.log('response.data的键:', Object.keys(response.data || {}));
        }

        // 获取货品ID - 尝试多种可能的响应格式
        let goodsId = null;

        // 尝试各种可能的字段名
        const possiblePaths = [
            () => response?.data?.id,
            () => response?.data?.Id,
            () => response?.data?.ID,
            () => response?.data?.goodsId,
            () => response?.data?.GoodsId,
            () => response?.id,
            () => response?.Id,
            () => response?.ID,
            () => response?.goodsId,
            () => response?.GoodsId,
            () => response?.data?.data?.id,
            () => response?.data?.result?.id
        ];

        for (let i = 0; i < possiblePaths.length; i++) {
            try {
                const value = possiblePaths[i]();
                if (value !== null && value !== undefined && value !== 0) {
                    goodsId = value;
                    console.log(`✓ 在路径 ${i} 找到货品ID: ${goodsId}`);
                    break;
                }
            } catch (e) {
                // 忽略错误，继续尝试下一个路径
            }
        }

        // 如果还是找不到，尝试智能搜索
        if (!goodsId) {
            console.log('⚠ 常规路径未找到ID，开始智能搜索...');

            // 递归搜索对象中所有可能是ID的数字字段
            const findPossibleId = (obj, path = '') => {
                if (!obj || typeof obj !== 'object') return null;

                for (const key in obj) {
                    const value = obj[key];
                    const currentPath = path ? `${path}.${key}` : key;

                    // 检查是否是ID类似的字段名
                    const isIdLikeKey = /id/i.test(key);

                    // 如果值是数字且字段名包含id
                    if (isIdLikeKey && typeof value === 'number' && value > 0) {
                        console.log(`  → 找到可能的ID字段: ${currentPath} = ${value}`);
                        return { path: currentPath, value: value };
                    }

                    // 递归搜索
                    if (typeof value === 'object' && value !== null) {
                        const found = findPossibleId(value, currentPath);
                        if (found) return found;
                    }
                }
                return null;
            };

            const found = findPossibleId(response);
            if (found) {
                goodsId = found.value;
                console.log(`✓ 智能搜索找到货品ID: ${goodsId} (位置: ${found.path})`);
            }
        }

        console.log('==============================');
        console.log('最终提取到的货品ID:', goodsId);
        console.log('货品ID类型:', typeof goodsId);
        console.log('货品ID是否有效:', !!goodsId);
        console.log('==============================');

        if (response?.status || response?.success) {
            console.log('✓ 货品添加成功');

            // 检查是否获取到货品ID
            if (!goodsId) {
                console.error('❌ 错误：货品添加成功，但无法从响应中提取货品ID');
                console.error('请检查API响应格式，或联系后端开发人员');
                console.error('完整响应对象:', response);

                // 如果有库存数据，询问用户是否手动输入ID
                if (formData.initInventory && formData.inventoryList.length > 0) {
                    ElMessageBox.prompt('货品添加成功，但无法自动获取货品ID。\n\n请到货品列表中查看刚添加的货品ID，并在下方输入以保存库存数据：', '手动输入货品ID', {
                        confirmButtonText: '确定并保存库存',
                        cancelButtonText: '稍后手动添加',
                        inputPattern: /^\d+$/,
                        inputErrorMessage: '请输入有效的数字ID',
                        inputPlaceholder: '请输入货品ID'
                    }).then(async ({ value }) => {
                        const manualId = parseInt(value);
                        console.log('用户手动输入的货品ID:', manualId);

                        if (manualId > 0) {
                            console.log('使用手动输入的ID保存库存和批次数据...');
                            await saveInventoryData(manualId);
                            console.log('库存和批次数据保存流程完成');
                        }
                    }).catch(() => {
                        console.log('用户取消手动输入ID');
                        ElMessage.warning({
                            message: '已跳过库存保存。请在货品列表中找到刚添加的货品，手动添加库存和批次信息。',
                            duration: 5000
                        });
                    });
                } else {
                    ElMessage.error({
                        message: '货品添加成功，但无法获取货品ID。请查看控制台了解详情。',
                        duration: 5000
                    });
                }
            } else {
                // 成功获取到货品ID
                console.log(`✓ 成功获取货品ID: ${goodsId}`);

                // 如果启用了初始库存且有库存数据，则添加库存信息
                if (formData.initInventory && formData.inventoryList.length > 0) {
                    console.log('检测到启用初始库存，开始保存库存和批次数据...');
                    await saveInventoryData(goodsId);
                    console.log('库存和批次数据保存流程完成');
                } else {
                    if (!formData.initInventory) {
                        console.log('未启用初始库存，跳过库存数据保存');
                    } else if (formData.inventoryList.length === 0) {
                        console.log('没有库存数据，跳过保存');
                    }
                    ElMessage.success('货品添加成功');
                }
            }

            // 延迟跳转，确保用户能看到提示信息
            setTimeout(() => {
                router.push('/productinformationmodel');
            }, 1500);
        } else {
            ElMessage.error(response?.message || '添加失败');
        }
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error(error?.response?.data?.message || error?.message || '添加货品失败');
    } finally {
        submitLoading.value = false;
    }
};

// 保存库存数据
const saveInventoryData = async (goodsId) => {
    let successCount = 0;
    let failCount = 0;
    let batchSuccessCount = 0;
    let batchFailCount = 0;

    try {
        console.log('=== 开始保存库存数据 ===');
        console.log('货品ID:', goodsId);
        console.log('库存列表总数:', formData.inventoryList.length);

        // 遍历库存列表，调用添加库存接口
        for (const inventory of formData.inventoryList) {
            // 跳过没有选择仓库的行
            if (!inventory.warehouseId) {
                console.log(`跳过未选择仓库的行: ${inventory.warehouseName}`);
                continue;
            }

            console.log(`\n--- 处理仓库: ${inventory.warehouseName} (ID: ${inventory.warehouseId}) ---`);

            const inventoryData = {
                id: 0,
                goodsId: goodsId,
                warehouseId: inventory.warehouseId,
                batchNo: inventory.batchNo || 'string',
                currentQty: Number(inventory.initialQty) || 0,
                initialQty: Number(inventory.initialQty) || 0,
                importList: Number(inventory.initialQty) || 0,
                exportList: 0,
                lowerLimit: Number(inventory.lowerLimit) || 0,
                upperLimit: Number(inventory.upperLimit) || 0,
                expiryDate: inventory.expiryDate || '2025-10-30T08:03:07.743Z',
                remark: inventory.remark || 'string',
                creator: 'string',
                createDate: '2025-10-30T08:03:07.743Z',
                modifier: 'string',
                modifyDate: '2025-10-30T08:03:07.743Z',
                createID: 0,
                modifyID: 0
            };

            console.log('准备添加库存数据:', JSON.stringify(inventoryData, null, 2));

            try {
                const inventoryResponse = await proxy.http.post('/api/Inventory/AddInventory', inventoryData);

                console.log('库存添加API响应:', inventoryResponse);
                console.log('响应完整数据:', JSON.stringify(inventoryResponse, null, 2));

                if (inventoryResponse?.success || inventoryResponse?.status) {
                    console.log(`✓ 仓库 ${inventory.warehouseName} 的库存添加成功`);
                    successCount++;

                    // 如果该库存行有批次数据，则提交批次数据
                    if (inventory.batchList && inventory.batchList.length > 0) {
                        console.log(`\n--- 开始提交批次数据 (共 ${inventory.batchList.length} 条) ---`);
                        console.log('批次数据:', inventory.batchList);

                        try {
                            const batchResponse = await submitBatchData(goodsId, inventory.warehouseId, inventory.batchList);
                            if (batchResponse?.success || batchResponse?.status) {
                                console.log(`✓ 仓库 ${inventory.warehouseName} 的批次数据提交成功`);
                                batchSuccessCount++;
                            } else {
                                console.error(`✗ 仓库 ${inventory.warehouseName} 的批次数据提交失败:`, batchResponse?.message);
                                batchFailCount++;
                            }
                        } catch (batchError) {
                            console.error(`✗ 仓库 ${inventory.warehouseName} 的批次数据提交异常:`, batchError);
                            batchFailCount++;
                        }
                    } else {
                        console.log('该仓库没有批次数据');
                    }
                } else {
                    console.error(`✗ 仓库 ${inventory.warehouseName} 的库存添加失败:`, inventoryResponse?.message);
                    failCount++;
                }
            } catch (inventoryError) {
                console.error(`✗ 仓库 ${inventory.warehouseName} 的库存添加异常:`, inventoryError);
                failCount++;
            }
        }

        console.log('\n=== 库存数据保存完成 ===');
        console.log(`库存: 成功 ${successCount} 条, 失败 ${failCount} 条`);
        console.log(`批次: 成功 ${batchSuccessCount} 条, 失败 ${batchFailCount} 条`);

        // 显示结果提示
        if (failCount > 0 || batchFailCount > 0) {
            ElMessage.warning(`库存保存部分失败: 库存成功${successCount}条/失败${failCount}条, 批次成功${batchSuccessCount}条/失败${batchFailCount}条`);
        } else if (successCount > 0) {
            ElMessage.success(`库存和批次数据保存成功 (库存${successCount}条, 批次${batchSuccessCount}条)`);
        }
    } catch (error) {
        console.error('保存库存数据失败:', error);
        ElMessage.error('保存库存数据时发生错误: ' + (error?.message || '未知错误'));
    }
};

// 取消
const handleCancel = () => {
    router.push('/productinformationmodel');
};

// 页面加载时获取数据
onMounted(() => {
    loadProductTypes();
    loadSuppliers();
    loadUsers();
    loadUnits();
});
</script>

<style lang="less" scoped>
.product-add-container {
    padding: 20px;

    .page-header {
        margin-bottom: 20px;

        h2 {
            margin: 0;
            font-size: 20px;
            font-weight: 600;
            color: #303133;
        }
    }

    .form-container {
        .form-card {
            margin-bottom: 20px;

            .card-title {
                font-size: 16px;
                font-weight: 500;
                color: #303133;
            }
        }

        .unit-card {
            .unit-management {
                .unit-list {
                    margin-top: 20px;

                    .unit-item {
                        margin-bottom: 15px;
                        padding: 10px;
                        background-color: #f5f7fa;
                        border-radius: 4px;

                        &:hover {
                            background-color: #ecf5ff;
                        }

                        .required-mark {
                            color: #f56c6c;
                            font-size: 16px;
                            font-weight: bold;
                        }

                        .unit-label {
                            font-weight: 500;
                            color: #606266;
                        }

                        .unit-divider {
                            color: #909399;
                            font-size: 14px;
                            display: inline-block;
                            text-align: center;
                        }
                    }
                }
            }
        }

        .inventory-card {
            .card-header-wrapper {
                display: flex;
                align-items: center;
                width: 100%;
            }

            .inventory-error-tip {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 10px;
                background-color: #fef0f0;
                border: 1px solid #fde2e2;
                border-radius: 4px;
                color: #f56c6c;
                margin-bottom: 15px;
            }

            .inventory-management {
                .inventory-actions {
                    margin-bottom: 15px;
                }

                .inventory-table {
                    .amount-display {
                        padding: 8px;
                        text-align: center;
                        color: #606266;
                    }

                    .empty-tip {
                        padding: 40px 0;
                        text-align: center;

                        p {
                            margin: 0 0 15px 0;
                            color: #909399;
                            font-size: 14px;
                        }
                    }
                }
            }
        }

        .form-footer {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
        }
    }
}

.warehouse-dialog-content {
    .pagination-wrapper {
        display: flex;
        justify-content: center;
        margin-top: 20px;
    }

    :deep(.el-table__row) {
        cursor: pointer;

        &:hover {
            background-color: #f5f7fa;
        }
    }

    :deep(.current-row) {
        background-color: #ecf5ff !important;
    }
}

.batch-dialog-content {
    .batch-table {
        margin-bottom: 20px;
    }

    .batch-summary {
        padding: 15px;
        background-color: #f5f7fa;
        border-radius: 4px;
        text-align: right;
        font-size: 14px;
        color: #606266;

        .total-count {
            color: #67c23a;
            font-weight: bold;
            font-size: 16px;
            margin-left: 5px;
        }
    }
}
</style>
